import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
    return originalPush.call(this, location).catch(err => {})
};
Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        children: [{
            path: '/home/searchpopup',
            name: 'SearchPopup',
            component: () =>
                import ( /* webpackChunkName: "searchpopup" */ '../views/SearchPopup.vue')
        }],
        meta: {
            // 解决tabbar样式的小bug
            tabbarActiveNum: 0,
            // 是否展示tabbar
            isShowTabbar: true
        }
    },
    {
        path: '/topic',
        name: 'Topic',
        component: () =>
            import ( /* webpackChunkName: "topic" */ '../views/Topic.vue'),
        meta: {
            tabbarActiveNum: 1,
            isShowTabbar: true
        }
    },
    {
        path: '/category',
        name: 'Category',
        component: () =>
            import ( /* webpackChunkName: "category" */ '../views/Category.vue'),
        meta: {
            tabbarActiveNum: 2,
            isShowTabbar: true
        }
    },
    {
        path: '/cart',
        name: 'Cart',
        component: () =>
            import ( /* webpackChunkName: "cart" */ '../views/Cart.vue'),
        meta: {
            tabbarActiveNum: 3,
            isShowTabbar: true
        }
    },
    {
        path: '/user',
        name: 'User',
        component: () =>
            import ( /* webpackChunkName: "user" */ '../views/User.vue'),
        meta: {
            tabbarActiveNum: 4,
            isShowTabbar: true
        }
    },
    {
        path: "/productdetail",
        component: () =>
            import ( /* webpackChunkName: "productdetail" */ '../views/ProductDetail.vue'),
        meta: {
            isShowTabbar: false
        }
    }

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 每次路由发生变化都执行这里的代码,太消耗性能了,我们不这么写,把路由拦截写在要需要拦截的组件里面
// 全局路由守卫/路由拦截 能够在每一次跳转路由之前拦截下来,做一定的逻辑处理
// router.beforeEach((to, from, next) => {
// 什么时候跑这里的代码? 路由发生变化之前执行
// console.log("beforeEach执行了");

// console.log("to是", to); //要去往路由的对象
// console.log("from是", from); //从哪里出发的这个路由对象

// 判断是不是要进入购物车
// if (to.path == "/cart") {
//     // console.log("进入到购物车");
//     // 判断有没有登录
//     // 如果没有登录，跳转到 /user 页面
//     let token = localStorage.getItem("token")
//     if (token) {
//         next()
//     } else {
//         // this.$toast("请先登录!")  这里的this是指Vue实例,在vue中可以使用,但是在这里,this就指向全局了,不能这么写
//         Vue.prototype.$toast("请先登录!")
//             // 拿不到token,说明没有登录,跳转到"我的" /user
//         setTimeout(() => {
//             next("/user")
//         }, 800);
//     }
//     return
// }

// next()
// })

export default router